package com.xmbandu.app.home;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.allenliu.versionchecklib.callback.APKDownloadListener;
import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.android.tu.loadingdialog.LoadingDailog;
import com.everobo.robot.sdk.ReadBookInterface;
import com.everobo.robot.sdk.interfac.RestigerInterfaceCallBack;
import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.xmbandu.app.R;
import com.xmbandu.app.activity.BookListActivity;
import com.xmbandu.app.activity.H5PayActivity;
import com.xmbandu.app.activity.LoginActivity;
import com.xmbandu.app.activity.SearchActiviy;
import com.xmbandu.app.activity.SspCommonWebActivity;
import com.xmbandu.app.activity.guide.SplashOneActivity;
import com.xmbandu.app.base.BaseActivity;
import com.xmbandu.app.base.GlideApp;
import com.xmbandu.app.base.SspConfig;
import com.xmbandu.app.bean.DeviceIdBean;
import com.xmbandu.app.bean.LinkBean;
import com.xmbandu.app.bean.StatusBean;
import com.xmbandu.app.home.fragment.SimpleCardFragment;
import com.xmbandu.app.httpnet.BaseObserver;
import com.xmbandu.app.httpnet.RetrofitFactory;
import com.xmbandu.app.qrcode.activity.CaptureActivity;
import com.xmbandu.app.utils.AppInstallUtils;
import com.xmbandu.app.utils.CommonUtils;
import com.xmbandu.app.utils.ConfigUtils;
import com.xmbandu.app.utils.DataCleanUtil;
import com.xmbandu.app.utils.SspPrefUtils;
import com.xmbandu.app.utils.ViewFindUtils;
import com.xmbandu.app.bean.UpdateBean;
import com.xmbandu.app.httpnet.BaseEntity;
import com.xmbandu.app.utils.NetUtil;
import com.xmbandu.app.view.OnDialogClickListener;
import com.xmbandu.app.view.ProgressButton;
import com.xmbandu.app.view.RxDialogSureCancel;
import com.xmbandu.app.view.TabRadioButton;
import com.xmbandu.app.view.UpdateDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

import java.io.File;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends BaseActivity {
    private RxPermissions permissions;

    private CompositeDisposable disposable;

    private FrameLayout flLeft;
    private FrameLayout flCenter;
    private FrameLayout flRight;
    private RadioGroup radioGroup;
    private TabRadioButton tbLift;
    private TabRadioButton tbRight;
    private ImageView fabCenter;
    private RelativeLayout search;
    private ImageView gif_img;
    private LinearLayout loginout;
    private LinearLayout bookCity;
    //定义一个变量，来标识是否退出
    private static boolean isExit = false;
    private AlertDialog dialog;
    String url = "https://item.taobao.com/item.htm?spm=a1z10.1-c-s.w4004-21619375264.2.52d2947beRai80&id=593322784139";


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    // 左侧书单相关
    private ArrayList<SimpleCardFragment> mFragments = new ArrayList<>();
    private String[] mTitles = {"教育", "故事"};
    private View mDecorView;
    private SegmentTabLayout mTabLayout;

    //右侧UI控件
    private LinearLayout ly_pel_update;
    private LinearLayout ly_pel_video;
    private LinearLayout ly_per_clear;
    private LinearLayout book_list;
    //版本更新
    private DownloadBuilder builder;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @SuppressLint("NewApi")
    @Override
    public void initViews() {
        permissions = new RxPermissions(this);
        disposable = new CompositeDisposable();
        flLeft = findViewById(R.id.fl_left);
        flCenter = findViewById(R.id.fl_center);
        flRight = findViewById(R.id.fl_right);
        radioGroup = findViewById(R.id.radio_group);
        tbLift = findViewById(R.id.rb_left);
        tbRight = findViewById(R.id.rb_right);
        fabCenter = findViewById(R.id.bt_center);
        search = findViewById(R.id.layout_search);
        gif_img = findViewById(R.id.gif_img);
        GlideApp.with(this).asGif().load(R.drawable.home_gif).centerInside().into(gif_img);
        //initTab();
    }

    @Override
    public void initListener() {
        setOnClick(tbLift);
        setOnClick(tbRight);
        setOnClick(fabCenter);
        setOnClick(search);
    }

    @Override
    public void initData() {
        getLink();

    }

    @Override
    public void processClick(View v) {
        switch (v.getId()) {
            case R.id.rb_left:
                // TODO: 2019-04-25 选中左边，显示左边儿ui
                radioGroup.check(R.id.rb_left);
                shoLeft();
                break;
            case R.id.rb_right:
                // TODO: 2019-04-25  选中右边，显示右边儿ui
                radioGroup.check(R.id.rb_right);
                showRight();
                break;
            case R.id.bt_center:
                if(CommonUtils.isClickable()){
                    checkLogin();
//                    gotoReadBook();

                }
//                radioGroup.clearCheck();

                break;
            case R.id.layout_search:
                Intent intent = new Intent(this, SearchActiviy.class);
                startActivity(intent);
                break;
        }
    }

    /**
     * 检查是否登录
     */
    private void checkLogin() {
        Observable observable = RetrofitFactory.getInstance().checkLogin();
        observable.compose(compose(this.bindToLifecycle())).subscribe(new BaseObserver(this) {
            @Override
            protected void onHandleSuccess(Object o) {
                Log.e("MainActivity", "onHandleSuccess: "+o.toString() );
//                gotoReadBook();

            }

            @Override
            public void onNext(Object o) {
                Log.e("MainActivity", "onNext: "+o.toString() );
                if(o.toString().contains("code=1")){
                    gotoReadBook();

                }else if(o.toString().contains("code=0")){
                    Intent intent = new Intent(MainActivity.this,LoginActivity.class);
                    startActivity(intent);
                    finish();
                }



            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);


            }
        });

    }

        private void getLink() {
        Observable observable = RetrofitFactory.getInstance().getLink();
        observable.compose(compose(this.bindToLifecycle())).subscribe(new BaseObserver<LinkBean>(this) {
            @Override
            protected void onHandleSuccess(LinkBean linkBean) {
                Log.e("GuideActivity", "onHandleSuccess: "+linkBean.getUrl() );
                if(!TextUtils.isEmpty(linkBean.getUrl())){
                    SspPrefUtils.setString("weburl",linkBean.getUrl());
                }

            }


        });
    }

    private void gotoReadBook() {
        permissions.request(Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    gotoPermissions();

                } else {
                    //只要有一个权限被拒绝，就会执行
                    Toast.makeText(MainActivity.this, "未授权权限，部分功能不能使用", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    // 初始化书单顶部tabLayout
    private void initTab() {
        for (String title : mTitles) {
            mFragments.add(SimpleCardFragment.getInstance(title));
        }
        mDecorView = getWindow().getDecorView();
        mTabLayout = ViewFindUtils.find(mDecorView, R.id.tl_2);
        initFragmentView();
    }

    // 初始化书单fragment
    private void initFragmentView() {
        final ViewPager viewPager = ViewFindUtils.find(mDecorView, R.id.viewpager);
        viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
        mTabLayout.setTabData(mTitles);
        mTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                viewPager.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {
            }
        });

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mTabLayout.setCurrentTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        // 设置书单fragment 默认选中
        viewPager.setCurrentItem(0);
    }

    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }

        @Override
        public SimpleCardFragment getItem(int position) {
            return mFragments.get(position);
        }
    }

    // 显示左侧UI
    private void shoLeft() {
        flLeft.setVisibility(View.VISIBLE);
        flCenter.setVisibility(View.GONE);
        flRight.setVisibility(View.GONE);
    }

    private void showCenter() {
        flLeft.setVisibility(View.GONE);
        flCenter.setVisibility(View.VISIBLE);
        flRight.setVisibility(View.GONE);
    }

    // 显示右侧UI
    private void showRight() {
        flLeft.setVisibility(View.GONE);
        flCenter.setVisibility(View.GONE);
        flRight.setVisibility(View.VISIBLE);
        initRightView();
    }

    // 初始化左侧UI
    private void initLeftView() {

    }

    // 初始化右侧UI
    private void initRightView() {
        /**
         * 书城
         */
        bookCity = findViewById(R.id.book_city);
        /**
         * 退出登陆
         */
        loginout = findViewById(R.id.login_out);
        /**
         * 清理缓存
         */
        ly_per_clear = findViewById(R.id.clear);
        /**
         * 检查更新
         */
        ly_pel_update = findViewById(R.id.ly_pel_update);
        /**
         * 视频课堂
         */
        ly_pel_video = findViewById(R.id.ly_pel_video);

        /**
         * 书单
         */
        book_list=findViewById(R.id.book_list);
        initStatus();
        ly_pel_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //检测更新
                disposable.add(
                        RetrofitFactory
                                .getInstance()
                                .update("android")
                                .subscribeOn(Schedulers.io())
                                .doOnSubscribe(new Consumer<Disposable>() {
                                    @Override
                                    public void accept(Disposable disposable) throws Exception {
                                        if (!NetUtil.isNetConnected(MainActivity.this)) {
                                            Toast.makeText(MainActivity.this, "　暂无网络！！！", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                })
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Consumer<BaseEntity<UpdateBean>>() {
                                    @Override
                                    public void accept(BaseEntity<UpdateBean> updateBeanBaseEntity) throws Exception {
                                        if (updateBeanBaseEntity.getData().getVersion_code() > ConfigUtils.getVersionCode()) {
                                            // 有更新,进行弹窗
                                            update(updateBeanBaseEntity.getData().getUrl(), updateBeanBaseEntity.getData().getInfo());
                                        } else {
                                            // 没有更新
                                            Toast.makeText(MainActivity.this,"已经是最新版本啦",Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                }, new Consumer<Throwable>() {
                                    @Override
                                    public void accept(Throwable throwable) throws Exception {

                                    }
                                })
                );


            }
        });

        ly_pel_video.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //视频课堂
                Toast.makeText(MainActivity.this, "敬请期待", Toast.LENGTH_LONG).show();
            }
        });
        //清理缓存
        ly_per_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DataCleanUtil.clearAllCache(MainActivity.this);
                Toast.makeText(MainActivity.this, "清理缓存成功", Toast.LENGTH_LONG).show();
            }
        });
        loginout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginOut();
            }
        });
        bookCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(TextUtils.isEmpty(SspPrefUtils.getString("weburl",""))){
                    H5PayActivity.intoSspCommonWeb(MainActivity.this,url);
                }
                H5PayActivity.intoSspCommonWeb(MainActivity.this,SspPrefUtils.getString("weburl",""));
//                if (AppInstallUtils.isTaoBaoAvailable(MainActivity.this)) {
//                    //跳转淘宝店铺
////                    String url = "https://m.tb.cn/h.e1sJjCi?sm=19ff2a";
//                    String url = "taobao://shop.m.taobao.com/shop/shop_index.htm?shop_id=268113955";
//                    Intent intent = new Intent();
//                    intent.setAction("Android.intent.action.VIEW");
//                    Uri uri = Uri.parse(url); // 商品地址
//                    intent.setData(uri);
//                    intent.setClassName("com.taobao.taobao","com.taobao.android.shop.activity.ShopHomePageActivity");
//                    startActivity(intent);
//                } else {
//                    /**
//                     * 可以使用webView进行打开
//                     */
//                    Toast.makeText(MainActivity.this, "请下载淘宝app再进行商品的购买!", Toast.LENGTH_SHORT).show();
//                }
            }
        });
        book_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              //  BookListActivity.start(MainActivity.this);
                H5PayActivity.intoSspCommonWeb(MainActivity.this,
                        "https://server.everobo.com/web/wxH5/bookSeek.html?from=groupmessage&isappinstalled=0","书单");
            }
        });
    }

    /**
     * 是否显示书城
     */
    private void initStatus() {
        Observable observable = RetrofitFactory.getInstance().getStatus();
        observable.compose(compose(this.bindToLifecycle())).subscribe(new BaseObserver<StatusBean>(this) {
            @Override
            protected void onHandleSuccess(StatusBean statusBean) {
                if(statusBean.getStatus()==0){//隐藏书城
                    bookCity.setVisibility(View.GONE);

                }else {//显示
                    bookCity.setVisibility(View.VISIBLE);
                }
            }


        });
    }


    /**
     * 申请权限
     */
    private void gotoPermissions() {
        if(SspPrefUtils.getBoolean("isfirst",true)){
                 SspPrefUtils.setBoolean("isfirst",false);
                    Intent intent = new Intent(this, SplashOneActivity.class);
                    intent.putExtra("tag",1);
                    startActivity(intent);

            }else {
                    // 二维码扫码
                    if(TextUtils.isEmpty(SspPrefUtils.getString("deviceid",""))){
                        Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
                        startActivityForResult(intent, SspConfig.REQ_QR_CODE);

                    }else {
                        LoadingDailog.Builder loadBuilder=new LoadingDailog.Builder(this)
                                .setMessage("加载中...")
                                .setCancelable(true)
                                .setCancelOutside(true);
                        final LoadingDailog dialog=loadBuilder.create();
                        dialog.show();
//                        //申请的权限全部允许
                            ReadBookInterface.register(SspPrefUtils.getString("deviceid",""), new RestigerInterfaceCallBack() {
                                @Override
                                public void succes(String s) {
                                    dialog.dismiss();
                                    ReadBookInterface.startRead(MainActivity.this);
//                        com.everobo.robot.phone.ui.MainActivity.gotoThis(MainActivity.this);
                                }

                                @Override
                                public void fail(Object o) {
                                    dialog.dismiss();
                                    Log.e("TAGGG", "登陆失败");
                                }
                            });
                        }

                    }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        if (requestCode == SspConfig.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(SspConfig.INTENT_EXTRA_KEY_QR_SCAN);
            //将扫描出的信息显示出来
//            tvResult.setText(scanResult);
//            getDeviceId(scanResult);
            Log.e("MainActivity", "onActivityResult: "+scanResult );
            bindDeviceId(scanResult);
        }
    }

    /**
     * 绑定deviceid
     * @param scanResult
     */
    private void bindDeviceId(String scanResult) {
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .addHeader("XX-Api-Version", "v1")
                .addHeader("XX-Token", SspPrefUtils.getString("token",""))
                .url(scanResult+"&source=app")
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("MainActivity", "onFailure: "+call.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.e("MainActivity", "onResponse: " + response.body().string());
                try {
                    JSONObject object = new JSONObject(response.body().string());
                    int code = object.getInt("code");
                    switch (code){
                        case 1:
                            JSONObject data  = object.getJSONObject("data");
                            String deviveid = data.getString("deviceid");
                            SspPrefUtils.setString("deviceid",deviveid);
                            final LoadingDailog.Builder loadBuilder=new LoadingDailog.Builder(MainActivity.this)
                                    .setMessage("加载中...")
                                    .setCancelable(true)
                                    .setCancelOutside(true);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    final LoadingDailog dialogs=loadBuilder.create();
                                    dialogs.show();
                                    //申请的权限全部允许
                                    if(SspPrefUtils.getBoolean("isfirst",true)){
                                        dialogs.dismiss();
                                        SspPrefUtils.setBoolean("isfirst",false);
                                        Intent intent = new Intent(MainActivity.this, SplashOneActivity.class);
                                        intent.putExtra("tag",0);
                                        startActivity(intent);
                                    }else {
                                        ReadBookInterface.register(SspPrefUtils.getString("deviceid",""), new RestigerInterfaceCallBack() {
                                            @Override
                                            public void succes(String s) {
                                                dialogs.dismiss();
                                                ReadBookInterface.startRead(MainActivity.this);
//                        com.everobo.robot.phone.ui.MainActivity.gotoThis(MainActivity.this);
                                            }

                                            @Override
                                            public void fail(Object o) {
                                                dialogs.dismiss();
                                                Log.e("TAGGG", "登陆失败");
                                            }
                                        });
                                    }
                                }
                            });



                            break;
                        case 10001:
                            Intent intent = new Intent(MainActivity.this,LoginActivity.class);
                            startActivity(intent);
                            finish();
                            break;
                        case 0:
                            if(object.getString("msg").equals("该设备已被他人绑定")){
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        DiyDialog("该设备已被他人绑定");//提示购买

                                    }
                                });
                            }else if(object.getString("msg").equals("您的账号已绑定其他设备")){//提示用户换个账号
                                Intent login = new Intent(MainActivity.this,LoginActivity.class);
                                startActivity(login);
                                finish();
                            }else {
                                Toast.makeText(MainActivity.this,object.getString("msg"),Toast.LENGTH_SHORT).show();
                            }
                            break;


                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    /**
     * 获取device
     */
    private void getDeviceId(String scanResult) {
        Observable observable = RetrofitFactory.getInstance().getDeviece(scanResult+"&source=app");
        observable.compose(compose(this.bindToLifecycle())).subscribe(new BaseObserver<DeviceIdBean>(this) {

            @Override
            protected void onHandleSuccess(DeviceIdBean deviceIdBean) {
                Log.e("deviceid", "onHandleSuccess: " + deviceIdBean.getDeviceid());
                Toast.makeText(MainActivity.this,"激活成功",Toast.LENGTH_SHORT).show();
                SspPrefUtils.setString("deviceid", deviceIdBean.getDeviceid());
                //申请的权限全部允许
                ReadBookInterface.register(SspPrefUtils.getString("deviceid",""), new RestigerInterfaceCallBack() {
                    @Override
                    public void succes(String s) {
                        ReadBookInterface.startRead(MainActivity.this);
//                        com.everobo.robot.phone.ui.MainActivity.gotoThis(MainActivity.this);
                    }

                    @Override
                    public void fail(Object o) {
                        Log.e("TAGGG", "登陆失败");
                    }
                });
//
            }

            @Override
            public void onNext(BaseEntity<DeviceIdBean> value) {
                super.onNext(value);
                String msg = value.getMsg();
                if(msg.equals("该设备已被他人绑定")){//提示用户购买
                    DiyDialog(msg);
                }

            }

            @Override
            protected void onHandleError(String msg) {
                super.onHandleError(msg);
                if(msg.equals("登录已失效!")){
                    Intent intent = new Intent(MainActivity.this,LoginActivity.class);
                    startActivity(intent);
                    finish();

                }

            }
        });
    }
    private void DiyDialog(String msg){
        //提示弹窗
        final RxDialogSureCancel rxDialogSureCancel = new RxDialogSureCancel(this);
        rxDialogSureCancel.getTitleView().setBackgroundResource(R.mipmap.logo);
        rxDialogSureCancel.getContentView().setText(msg+"是否购买新设备？");
        rxDialogSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(TextUtils.isEmpty(SspPrefUtils.getString("weburl",""))){
                    H5PayActivity.intoSspCommonWeb(MainActivity.this,url);
                }
                H5PayActivity.intoSspCommonWeb(MainActivity.this,SspPrefUtils.getString("weburl",""));
//                if (AppInstallUtils.isTaoBaoAvailable(MainActivity.this)) {
//                    //跳转淘宝店铺
//                    String url = "taobao://shop.m.taobao.com/shop/shop_index.htm?shop_id=268113955";
//                    Intent intent = new Intent();
//                    intent.setAction("Android.intent.action.VIEW");
//                    Uri uri = Uri.parse(url); // 商品地址
//                    intent.setData(uri);
//                    intent.setClassName("com.taobao.taobao","com.taobao.android.shop.activity.ShopHomePageActivity");
//                    startActivity(intent);
//                } else {
//                    Toast.makeText(MainActivity.this, "请下载淘宝app再进行商品的购买!", Toast.LENGTH_SHORT).show();
//                }
                rxDialogSureCancel.cancel();
            }
        });
        rxDialogSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rxDialogSureCancel.cancel();
            }
        });

        rxDialogSureCancel.show();
    }

    /**
     * 退出登录
     */
    private void loginOut() {
        Observable observable = RetrofitFactory.getInstance().loginOut();
        observable.compose(compose(bindToLifecycle())).subscribe(new BaseObserver(this) {
            @Override
            protected void onHandleSuccess(Object o) {

            }

            @Override
            public void onNext(Object o) {
                SspPrefUtils.setString("token", "");
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            //利用handler延迟发送更改状态信息
            handler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
            System.exit(0);
        }
    }

    private void update(final String downurl, String content) {
        final UpdateDialog updateDialog = new UpdateDialog(MainActivity.this, R.style.MyDialog, content);
        Window window = updateDialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams params = window.getAttributes();
        params.height = 1200;
        params.width = 700;
        window.setAttributes(params);
        updateDialog.setOnDialogClickListener(new OnDialogClickListener() {
            @Override
            public void onYesClick(Dialog dialog, final ProgressButton progressButton) {
                //立即更新的点击事件
                Log.d("wmq", "下载链接： " + downurl);
                builder = AllenVersionChecker.getInstance()
                        .downloadOnly(UIData.create().setDownloadUrl(downurl).setContent("").setTitle(""));

                builder.setDirectDownload(true);
                builder.setShowNotification(true);
                builder.setForceRedownload(false);
                builder.setShowDownloadFailDialog(false);
                builder.setShowDownloadingDialog(false);
                builder.executeMission(MainActivity.this);

                builder.setApkDownloadListener(new APKDownloadListener() {
                    @Override
                    public void onDownloading(int progress) {
                        progressButton.setText("");
                        progressButton.setProgress(progress);
                        progressButton.setEnabled(false);

                    }

                    @Override
                    public void onDownloadSuccess(File file) {
                        updateDialog.dismiss();

                    }

                    @Override
                    public void onDownloadFail() {
                        progressButton.setText(getResources().getString(R.string.btn_update));
                        progressButton.setEnabled(true);

                    }
                });


            }
        }).show();
    }

}
